package net.sansi.v3correctserver.entity.image;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import net.sansi.v3correctserver.entity.color.PhotoColor;
import net.sansi.v3correctserver.exception.ServiceException;
import net.sansi.v3correctserver.util.Matrix;
import org.apache.commons.imaging.ImageInfo;
import org.apache.commons.imaging.Imaging;
import org.apache.commons.imaging.bytesource.ByteSource;

import java.nio.file.Path;

/**
 * Created by Fang
 * create time : 2024/11/20
 * IDE : IntelliJ IDEA
 */

@Slf4j
@Getter
@Setter
public class RecTiffImage extends RecImageBase {

    Matrix<int[]> data;

    public RecTiffImage(Path path) {
        try {
            ImageInfo info = Imaging.getImageInfo(path.toFile());
            ByteSource byteSource = ByteSource.file(path.toFile());
            long size = byteSource.size();
            int w = info.getWidth(), h = info.getHeight();
            data = new Matrix<>(w, h);
            byte[] bytes = byteSource.getByteArray(0, (int) size);
            int start = (int) size - w * h * 6;
            for (int x = 0; x < w; x += 1) {
                for (int y = 0; y < h; y += 1) {
                    int p = (y * w + x) * 6 + start;
                    data.set(x, y, new int[]{
                            byte2Color(bytes, p, 2),
                            byte2Color(bytes, p + 2, 2),
                            byte2Color(bytes, p + 4, 2)
                    });
                }
            }
        } catch (Exception e) {
            throw new ServiceException("tiff文件解析失败！ {}", e.getMessage(), e);
        }

    }

    public int byte2Color(byte[] bytes, int start, int len) {
        int res = 0;
        for (int i = start + len - 1; i >= start; i--) {
            res = (res << 8) | (bytes[i] & 0xFF);
        }
        return res;
    }

    @Override
    public int getWidth() {
        return data.getWidth();
    }

    @Override
    public int getHeight() {
        return data.getHeight();
    }

    @Override
    public PhotoColor getPhotoColor(int x, int y) {
        return new PhotoColor(data.get(x, y));
    }
}
